const express = require('express');
const router = express.Router();
const createError = require('http-errors');
const Sale = require('../models/Sale');
const Purchase = require('../models/Purchase');
const Product = require('../models/Product');
const Supplier = require('../models/Supplier');
const { Op } = require('sequelize');

// 获取销售记录列表
router.get('/sales', async (req, res, next) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const size = parseInt(req.query.size) || 10;
    const { startDate, endDate } = req.query;

    // 构建查询条件
    const where = {};
    if (startDate && endDate) {
      where.createdAt = {
        [Op.between]: [
          new Date(startDate + ' 00:00:00'),
          new Date(endDate + ' 23:59:59')
        ]
      };
    }

    const { count, rows } = await Sale.findAndCountAll({
      where,
      include: [{
        model: Product,
        as: 'product',
        attributes: ['name', 'salePrice'],
        include: [{
          model: Supplier,
          as: 'supplier',
          attributes: ['name']
        }]
      }],
      order: [['createdAt', 'DESC']],
      offset: (page - 1) * size,
      limit: size
    });

    // 格式化返回数据
    const records = rows.map(record => ({
      id: record.id,
      goodsName: record.product.name,
      price: record.price,
      amount: record.quantity,
      total: record.total,
      supplierName: record.product.supplier.name,
      createTime: record.createdAt
    }));

    // 计算是否有更多数据
    const hasMore = page * size < count;

    res.json({
      list: records,
      total: count,
      page,
      size,
      hasMore
    });

  } catch (error) {
    next(error);
  }
});

// 获取进货记录列表
router.get('/purchase', async (req, res, next) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const size = parseInt(req.query.size) || 10;
    const { startDate, endDate } = req.query;

    // 构建查询条件
    const where = {};
    if (startDate && endDate) {
      where.createdAt = {
        [Op.between]: [
          new Date(startDate + ' 00:00:00'),
          new Date(endDate + ' 23:59:59')
        ]
      };
    }

    const { count, rows } = await Purchase.findAndCountAll({
      where,
      include: [{
        model: Product,
        as: 'product',
        attributes: ['name', 'purchasePrice'],
        include: [{
          model: Supplier,
          as: 'supplier',
          attributes: ['name']
        }]
      }],
      order: [['createdAt', 'DESC']],
      offset: (page - 1) * size,
      limit: size
    });

    // 格式化返回数据
    const records = rows.map(record => ({
      id: record.id,
      goodsName: record.product.name,
      amount: record.quantity,
      supplierName: record.product.supplier.name,
      createTime: record.createdAt,
      remark: record.remark,
      price: record.price,
      total: record.total
    }));

    // 计算是否有更多数据
    const hasMore = page * size < count;

    res.json({
      list: records,
      total: count,
      page,
      size,
      hasMore
    });

  } catch (error) {
    next(error);
  }
});

// 获取今日数据概览
router.get('/overview', async (req, res, next) => {
  try {
    // 获取今天的开始和结束时间
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    // 统计数据
    const [totalGoods, todaySales, todayPurchases] = await Promise.all([
      // 总商品数
      Product.count(),

      // 今日销售额
      Sale.sum('total', {
        where: {
          createdAt: {
            [Op.between]: [today, tomorrow]
          }
        }
      }),

      // 今日进货数
      Purchase.sum('quantity', {
        where: {
          createdAt: {
            [Op.between]: [today, tomorrow]
          }
        }
      })
    ]);

    res.json({
      totalGoods: totalGoods || 0,
      sales: todaySales || 0,
      purchase: todayPurchases || 0
    });

  } catch (error) {
    next(error);
  }
});

module.exports = router;
